<script lang="ts" setup>
import BottomButton from "./components/bottom-button.vue";
import Dispatch from "./components/dispatch.vue";
import LeftAlert from "./components/left-alert.vue";
import leftAdd from "../../components/left/leftAdd.vue";
// import * as T01Sip from "../../utils/tele_interface";
// const T01Sip = require("../../utils/tele_interface");
import topHeader from "../../layout/top-header/index.vue";
import MapWrapper from "../../components/map-wrapper/index.vue";
import { useNotification } from "naive-ui";
import { onMounted, ref } from "vue";
//@ts-ignore
import t01Sip from "t01Sip";
import { getOriginizationApi } from "../../api/index";
// import { Iotdevice } from "../../api/model"
import { useMainStore } from "@/store";
import callImg from "../../assets/images/call.png";
import videoImg from "../../assets/images/video.png";
import WebSocketComp from "../../components/websocket/index.vue";
import { isSlotEmpty } from "naive-ui/es/_utils";
const store = useMainStore();
const notification = useNotification();
let userAgent: any = {};
const videoRef = ref();
const videoRef2 = ref();
let curSession: any = {};
const sessionList = ref<Array<any>>([]);
const showPanel = ref(false);
const status = ref("");
const type = ref("");
const sourceList = ref<Array<any>>([]);
const localSource = ref<any>({});
// 控制组件切换
let handleShow: any = ref(true);
onMounted(() => {
  // console.log(t01Sip);
  check();
  register();

  // setInterval(()=>{
    getIcon()
  // },1000)
});
const check = () => {
  t01Sip.checkDeviceSupport().then((res) => {
    console.log(res);
  });
};

/**
 * 发起请求获取图标
 */
const getIcon = () => {
  // store.layers[2] = {}
  console.log('查看', store.layers[2])
  let layerChind = []

  // Iotdevice({ page: 1, size: 20 }).then((data: any) => {
  //   console.log('data', data.data.list)
  //   data.data.list.forEach((item: any) => {
  //     console.log('icon', item.icon)
  //     // @ts-ignore
  //     layerChind.push({
  //       id: item.id,
  //       size: 10,
  //       pos: { longtitude: item.location.x, latitude: item.location.y },
  //       // icon:item.icon
  //     })
  //   })
  // })

  store.layers[2] = {
    id: 3,
    name: '实时设备',
    type: "marker",
    visible: true,
    // icon: "https://xunjinasd.oss-cn-hangzhou.aliyuncs.com/app/space/78dfd3bd4b0a413197fa82811cf18d04_file14.png",
    icon: "https://rcs-bucket.oss-cn-hangzhou.aliyuncs.com/app/space/085b0d202b444cb9b86eea2d1204e69b_%E5%AE%9A%E4%BD%8D.png",
    children: layerChind
  }
  console.log('store', store.layers[2], store.layers[2].icon)
}

const getIcon2 = () => {

}

const isRegister = ref(false);
const register = () => {
  // console.log('调用了')
  // let res: any = store.resData
  t01Sip
    .register({
      url: "/RcsProxy",
      userId: "70000177",
      userPwd: "1234",
      userType: 2,
      devType: "WEB",
    })
    .then((res) => {
      console.log('res', res);
      // if (res.userInfo.result == "用户已登录") {
      //   notification.error({
      //     content: res.userInfo.result,
      //     duration: 3000,
      //   });
      //   return;
      // }
      // res.userInfo.cmd.HOST = "1.116.178.22";
      store.$patch({
        userInfo: res.userInfo,
      });
      // res.userAgent.configuration.via_host = "1.116.178.22";
      //@ts-ignore
      window.userAgent = res.userAgent;
      console.log(res.userAgent);
      userAgent = res.userAgent;
      isRegister.value = true;

      userAgent.on("connecting", function (data) {
        console.log("connect", data);
        //data.socket//正在链接的实例
        //data.attempts//尝试链接的次数
      });
      userAgent.on("connected", function (data) {
        console.log("connected", data);
        //data.socket//链接的实例
      });
      userAgent.on("disconnected", function (data) {
        console.log("disconnected", data);
        //data.socket//实例
        //data.error //Boolean类型,表示是否因socket错误断开，（true/false）
        //data.code //socket错误代码
        //data.reason //socket错误原因
      });
      userAgent.on("newRTCSession", function (data) {
        var originator = data.originator; //'remote'为对方来电，‘local’为本方呼叫
        var session = data.session; //session会话实例
        var request = data.request.body; //对方或己方发出的请求实例
        curSession = session;

        showPanel.value = true;
        status.value = "正在接通中...";
        // 获取呼叫的类型
        type.value =
          originator === "remote"
            ? request.indexOf("video") > -1
              ? "video"
              : "audio"
            : "";
        // 主叫人号码
        var fromNum = data.request.from._uri._user;
        // 被叫人号码
        var toNum =
          originator === "remote"
            ? "远程呼入的可自己登录号码"
            : data.request.to._uri._user;
        console.log(session);
        // 如果有多路通路请参考6.5.1
        data.session.on("confirmed", function (data) {
          status.value = "已接通";
          sessionList.value.push(session);
          // 监听接听事件处理
          console.log(data, "confirmed");
          if (!localSource.value) {
            localSource.value = session.connection.getLocalStreams()[0];
          }
        });
        data.session.on("ended", function (data) {
          status.value = "已结束";
          // 监听结束事件处理
          console.log(data, "ended");
          // sessionList.value.splice
          setTimeout(() => {
            for (let i = 0; i < sessionList.value.length; i++) {
              if (sessionList.value[i].id == session.id) {
                sessionList.value.splice(i, 1);
                if (sessionList.value.length == 0) {
                  showPanel.value = false;
                }
                return;
              }
            }
          }, 1000);
        });
        data.session.on("failed", function (data) {
          // 监听失败事件处理

          console.log(data, "failed");
          // setTimeout(() => terminate(), 1000);
          notification.warning({
            content: data.cause,
          });
        });
        console.log(type.value);
        if (type.value) {
          t01Sip.answer({
            session,
            type: type.value,
          });
        }
      });
      // call();
      // getOrginization();
    });
};

const call = () => {
  console.log(t01Sip.call({}));
};
const terminateAll = () => {
  showPanel.value = false;
  sessionList.value.forEach((session) => {
    session.terminate();
  });
  sessionList.value = [];
};
const terminate = () => {
  showPanel.value = false;
  if (curSession.terminate) {
    curSession.terminate();
  }
};

/**
 * 控制组件切换
 */
const handleComponent = () => {
  handleShow.value = !handleShow.value;
  // console.log('触发了')
  // handleShow.value = test
};
</script>

<template>
  <div class="home-wrapper">
    <!-- -------- -->
    <topHeader></topHeader>
    <MapWrapper>
      <!-- ----------------- -->
      <div class="home-page">
        <!-- 主业左边组件 -->
        <div class="left" v-show="handleShow">
          <LeftAlert @handleComponent="handleComponent"></LeftAlert>
        </div>
        <div class="left" v-show="!handleShow">
          <leftAdd @handleComponent="handleComponent"></leftAdd>
        </div>
        <!-- 主页右边组件 -->
        <div class="right">
          <Dispatch v-if="isRegister"></Dispatch>
        </div>
      </div>
      <div v-show="showPanel" class="mask">
        <div class="media-panel">
          <div class="status">{{ status }}</div>
          <div class="dialog-wrapper">
            <video :style="{
              backgroundImage: `url(${type == 'audio' ? callImg : videoImg})`,
            }" autoplay :srcObject="localSource"></video>
            <div class="session-list" v-for="session in sessionList">
              <div class="remoteList" v-if="session.connection" v-for="source in session.connection.getRemoteStreams()">
                <video :style="{
                  backgroundImage: `url(${type == 'audio' ? callImg : videoImg
                    })`,
                }" autoplay :srcObject="source"></video>
              </div>
            </div>
          </div>

          <div @click="terminateAll" class="close">挂断</div>
        </div>
      </div>
      <!-- -------- -->
    </MapWrapper>
    <!-- ------------- -->
    <BottomButton></BottomButton>
    <WebSocketComp></WebSocketComp>
  </div>
</template>

<style lang="scss" scoped>
.home-wrapper {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  // background-color: var(--color-bg-dark);
  background-image: url("https://xunjinasd.oss-cn-hangzhou.aliyuncs.com/app/space/b4364d3f41e14370887dba41df6ee239_u0_state0.jpg");
  width: 100vw;
  height: 100vh;
  overflow: scroll;
  color: #fff;
  box-sizing: border-box;
}

.home-page {
  display: flex;
  justify-content: space-between;
  overflow-y: scroll;
  margin-top: 20px;
}

.left {
  // z-index: 15;
}

.center {
  margin: 0 15px;
  box-sizing: border-box;
  width: 100%;
}

.slot {
  width: 100%;
  height: 600px;
  background-color: rgba(0, 0, 0, 0.5);
  margin-bottom: 15px;
}

.mask {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  left: 0px;
  top: 0px;
  z-index: 100;
  backdrop-filter: blur(2px);
}

.media-panel {
  width: 600px;
  background-color: #ffffffee;
  padding: 30px 0;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  color: #333;

  .close {
    width: 300px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ea2f2f;
    border-radius: 8px;
    color: #fff;
    cursor: pointer;
    user-select: none;
  }

  .close:hover {
    opacity: 0.8;
  }

  .close:active {
    opacity: 1;
    color: #000;
  }

  .status {
    font-size: 20px;
  }

  .dialog-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;

    video {
      width: 220px;
      height: 220px;
      margin: 15px;
      background-color: rgba(0, 0, 0, 0.1);
      background-repeat: no-repeat;
      background-position: 50% 50%;
    }

    .remoteList {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    .session-list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }
  }
}
</style>
